import router from '@/router'

import { useUserStore } from '@/store/user'

import { getMenu, getToken, getUserinfo, removeAll, removeMenu, removeUserinfo } from '@/utils/auth' // get token from cookie

import 'nprogress/nprogress.css' // progress bar style
import NProgress from 'nprogress' // progress bar

const { configure, start, done } = NProgress
configure({ showSpinner: false }) // NProgress Configuration

const whiteList = ['/login', '/demo'] // no redirect whitelist

router.beforeEach(async (to: any, from: any, next) => {
  // start progress bar
  start()
  const hasToken = getToken()
  // const hasAuth = getUserinfo()?.uid
  const { asyncRoutes, setRoutes } = useUserStore()
  if (hasToken) {
    if (asyncRoutes.length === 0) {
      const menus = getMenu()
      if (menus) {
        const formatRoutes = setRoutes(menus)

        if (to.path === '/login') {
          next({ path: formatRoutes[0].path, replace: true })
        } else if (to.path === '/') {
          next({ path: formatRoutes[0].path, replace: true })
        } else {
          next({ ...to, replace: true })
          // next()
        }
      } else {
        // 清除信息 重新登录
        removeAll()
        next('/login')
      }
    } else {
      if (to.path === '/login') {
        next({ path: asyncRoutes[0].path, replace: true })
      } else if (to.path === '/') {
        next({ path: asyncRoutes[0].path, replace: true })
      } else {
        next()
      }
    }
  } else {
    getMenu() && removeMenu()
    getUserinfo() && removeUserinfo()
    /* has no token*/
    // next()
    if (whiteList.includes(to.path)) {
      // in the free login whitelist, go directly
      next()
    } else {
      // other pages that do not have permission to access are redirected to the login page.

      next('/login')
      // done()
    }
  }
})

router.afterEach(() => {
  // finish progress bar
  done()
})
